package com.scale.service.voice.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.nio.file.Files;

/**
 * 语音文件访问控制器
 * @author crp
 * @since 2025-09-28
 */
@RestController
@RequestMapping("/voice")
@Tag(name = "语音文件", description = "语音文件访问接口")
public class VoiceFileController {
    
    private static final Logger log = LoggerFactory.getLogger(VoiceFileController.class);
    
    /**
     * 🔧 从配置文件读取语音文件存储的绝对路径
     * 默认值作为fallback，实际应该在application.yml中配置
     */
    @Value("${voice.storage.base-path:D:/programme/javaEE/scale/data/voice}")
    private String basePath;
    
    /**
     * 获取语音文件
     */
    @GetMapping("/{year}/{month}/{day}/{filename:.+}")
    @Operation(summary = "获取语音文件", description = "根据路径获取语音文件")
    public ResponseEntity<Resource> getVoiceFile(
            @Parameter(description = "年份") @PathVariable String year,
            @Parameter(description = "月份") @PathVariable String month,
            @Parameter(description = "日期") @PathVariable String day,
            @Parameter(description = "文件名") @PathVariable String filename) {
        
        try {
            // 🔧 修复：构建正确的绝对文件路径
            String relativePath = String.format("%s/%s/%s/%s", year, month, day, filename);
            String fullPath = basePath + File.separator + relativePath.replace("/", File.separator);
            File file = new File(fullPath);
            
            log.info("🎵 请求语音文件: voice/{}", relativePath);
            log.info("🎵 实际文件路径: {}", fullPath);
            
            if (!file.exists() || !file.isFile()) {
                log.warn("⚠️ 语音文件不存在: {}", fullPath);
                
                // 🔧 添加调试信息
                log.info("🔍 调试信息:");
                log.info("   - 配置的基础路径: {}", basePath);
                log.info("   - 相对路径: {}", relativePath);
                log.info("   - 完整路径: {}", fullPath);
                log.info("   - 文件存在: {}", file.exists());
                log.info("   - 是否为文件: {}", file.exists() ? file.isFile() : "文件不存在");
                
                // 检查父目录是否存在
                File parentDir = file.getParentFile();
                if (parentDir != null) {
                    log.info("   - 父目录存在: {}", parentDir.exists());
                    if (parentDir.exists()) {
                        log.info("   - 父目录内容: {}", String.join(", ", parentDir.list() != null ? parentDir.list() : new String[]{}));
                    }
                }
                
                return ResponseEntity.notFound().build();
            }
            
            // 创建资源
            Resource resource = new FileSystemResource(file);
            
            // 确定媒体类型
            MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
            String contentType = Files.probeContentType(file.toPath());
            if (contentType != null) {
                if (contentType.startsWith("audio/")) {
                    mediaType = MediaType.parseMediaType(contentType);
                } else if (filename.toLowerCase().endsWith(".wav")) {
                    mediaType = MediaType.parseMediaType("audio/wav");
                } else if (filename.toLowerCase().endsWith(".mp3")) {
                    mediaType = MediaType.parseMediaType("audio/mpeg");
                } else if (filename.toLowerCase().endsWith(".mp4")) {
                    mediaType = MediaType.parseMediaType("audio/mp4");
                }
            }
            
            log.info("✅ 返回语音文件: {}, 类型: {}, 大小: {} 字节", 
                filename, mediaType, file.length());
            
            // 构建响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(mediaType);
            headers.setContentLength(file.length());
            headers.set("Accept-Ranges", "bytes");
            headers.set("Cache-Control", "public, max-age=86400"); // 24小时缓存
            
            // 添加CORS头
            headers.set("Access-Control-Allow-Origin", "*");
            headers.set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
            headers.set("Access-Control-Allow-Headers", "*");
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
                    
        } catch (Exception e) {
            log.error("❌ 获取语音文件失败: {}/{}/{}/{}", year, month, day, filename, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    /**
     * 处理OPTIONS预检请求
     */
    @RequestMapping(value = "/**", method = RequestMethod.OPTIONS)
    public ResponseEntity<Void> handleOptions() {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Access-Control-Allow-Origin", "*");
        headers.set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
        headers.set("Access-Control-Allow-Headers", "*");
        headers.set("Access-Control-Max-Age", "86400");
        
        return ResponseEntity.ok().headers(headers).build();
    }
}
